<?php

namespace platform\models;

use platform\core\BaseModel;
use cm;
use Yii;
use yii\helpers\Url;

class MainModel extends BaseModel
{
    /*
    * 首页
    */
    public function actionIndex()
    {
        $this->refreshorder();
        if (Cm::$req->isPost()) {
            $action = Cm::$req->get('action');
            switch ($action) {
                case 'stat-today':
                    //今日统计
                    $sdate = date('Y-m-d 00:00:00');
                    $edate = date('Y-m-d 23:59:59');
                    $statSql = "SELECT 'register' AS type,0 AS price,COUNT(id) AS num  FROM user WHERE status=1 AND addtime>='{$sdate}' AND addtime <= '{$edate}'
                                UNION ALL
                                SELECT 'order' AS type,SUM(order_price) AS price,COUNT(id) AS num  FROM `order` WHERE status=1 AND order_status!=5 AND addtime>='{$sdate}' AND addtime <= '{$edate}'
                                UNION ALL
                                SELECT 'passenger' AS type,0 AS price,COUNT(b.id) AS num  FROM `order` a LEFT JOIN order_passenger b ON b.order_id=a.id WHERE b.status AND a.status=1 AND a.order_status!=5 AND a.addtime>='{$sdate}' AND a.addtime <= '{$edate}'
                                UNION ALL
                                SELECT 'shift' AS type,0 AS price,COUNT(aa.shift_id) AS num  FROM (SELECT shift_id FROM `order` WHERE status=1 AND order_status!=5 AND addtime>='{$sdate}' AND addtime <= '{$edate}' GROUP BY shift_id) aa
                                UNION ALL
                                SELECT 'circuit' AS type,0 AS price,COUNT(aa.circuit_id) AS num  FROM (SELECT circuit_id FROM `order` WHERE status=1 AND order_status!=5 AND addtime>='{$sdate}' AND addtime <= '{$edate}' GROUP BY circuit_id) aa
                                UNION ALL
                                SELECT 'noorder' AS type,SUM(order_price) AS price,COUNT(id) AS num  FROM `order` WHERE (status IN (0,1,2,4) AND order_status=5) AND addtime>='{$sdate}' AND addtime <= '{$edate}'";
                    $stat = Cm::$db->all($statSql);
                    $info = [];
                    foreach ($stat as $s) {
                        $s['price'] = $s['price'] ? $s['price'] : 0;
                        $s['num'] = $s['num'] ? $s['num'] : 0;
                        $info[$s['type']] = $s;
                    }
                    Cm::$res->susess($info);
                    break;
                case 'stat-all':
                    //总计
                    $statSql = "SELECT 'register' AS type,0 AS price,COUNT(id) AS num  FROM user WHERE status=1 
                                UNION ALL
                                SELECT 'order' AS type,SUM(order_price) AS price,COUNT(id) AS num  FROM `order` WHERE status=1 AND order_status!=5
                                UNION ALL
                                SELECT 'passenger' AS type,0 AS price,COUNT(b.id) AS num  FROM `order` a LEFT JOIN order_passenger b ON b.order_id=a.id WHERE b.status AND a.status=1 AND a.order_status!=5
                                UNION ALL
                                SELECT 'shift' AS type,0 AS price,COUNT(aa.shift_id) AS num  FROM (SELECT shift_id FROM `order` WHERE status=1 AND order_status!=5 GROUP BY shift_id) aa
                                UNION ALL
                                SELECT 'circuit' AS type,0 AS price,COUNT(aa.circuit_id) AS num  FROM (SELECT circuit_id FROM `order` WHERE status=1 AND order_status!=5 GROUP BY circuit_id) aa
                                UNION ALL
                                SELECT 'noorder' AS type,SUM(order_price) AS price,COUNT(id) AS num  FROM `order` WHERE status IN (0,1,2,4) AND order_status=5";
                    $stat = Cm::$db->all($statSql);
                    $info = [];
                    foreach ($stat as $s) {
                        $s['price'] = $s['price'] ? $s['price'] : 0;
                        $s['num'] = $s['num'] ? $s['num'] : 0;
                        $info[$s['type']] = $s;
                    }
                    Cm::$res->susess($info);    
                    break;
                case 'stat-days':
                    $day = 7;
                    $sdate = date('Y-m-d 00:00:00', strtotime("-{$day} day"));
                    $edate = date('Y-m-d 23:59:59');
                    $sql = "SELECT 'order' AS type,date_format(addtime, '%Y-%m-%d') AS date,SUM(order_price) as price,count(id) AS num FROM `order` WHERE status=1 AND order_status!=5 AND addtime>='{$sdate}' AND addtime<='{$edate}' GROUP BY date_format(addtime, '%Y-%m-%d')
                            UNION ALL
                            SELECT 'noorder' AS type,date_format(addtime, '%Y-%m-%d') AS date,SUM(order_price) as price,count(id) AS num FROM `order` WHERE (status IN (0,1,2,4) AND order_status=5) AND addtime>='{$sdate}' AND addtime<='{$edate}' GROUP BY date_format(addtime, '%Y-%m-%d')
                            UNION ALL
                            SELECT 'nopay' AS type,date_format(addtime, '%Y-%m-%d') AS date,SUM(order_price) as price,count(id) AS num FROM `order` WHERE status=1 AND order_status=0 AND addtime>='{$sdate}' AND addtime<='{$edate}' GROUP BY date_format(addtime, '%Y-%m-%d')
                            UNION ALL
                            SELECT 'paynocar' AS type,date_format(addtime, '%Y-%m-%d') AS date,SUM(order_price) as price,count(id) AS num FROM `order` WHERE status=1 AND order_status=1 AND addtime>='{$sdate}' AND addtime<='{$edate}' GROUP BY date_format(addtime, '%Y-%m-%d')
                            UNION ALL
                            SELECT 'paycar' AS type,date_format(addtime, '%Y-%m-%d') AS date,SUM(order_price) as price,count(id) AS num FROM `order` WHERE status=1 AND order_status=2 AND addtime>='{$sdate}' AND addtime<='{$edate}' GROUP BY date_format(addtime, '%Y-%m-%d')
                            UNION ALL
                            SELECT 'startcar' AS type,date_format(addtime, '%Y-%m-%d') AS date,SUM(order_price) as price,count(id) AS num FROM `order` WHERE status=1 AND order_status=3 AND addtime>='{$sdate}' AND addtime<='{$edate}' GROUP BY date_format(addtime, '%Y-%m-%d')
                            UNION ALL
                            SELECT 'endcar' AS type,date_format(addtime, '%Y-%m-%d') AS date,SUM(order_price) as price,count(id) AS num FROM `order` WHERE status=1 AND order_status=4 AND addtime>='{$sdate}' AND addtime<='{$edate}' GROUP BY date_format(addtime, '%Y-%m-%d')";
                    $list = Cm::$db->all($sql);

                    $dates = [];
                    $_days = [];
                    for ($d = $day - 1; $d >= 0; $d--) {
                        $_d = date('Y-m-d', strtotime("-{$d} day"));
                        $dates[$_d] = 0;
                        $_days[] = $_d;
                    }

                    $types = [
                        'order' => ['price' => '有效订单金额'],
                        'noorder' => ['price' => '无效订单金额'],
                        'nopay' => ['num' => '未支付'],
                        'paynocar' => ['num' => '未派车'],
                        'paycar' => ['num' => '待出发'],
                        'startcar' => ['num' => '已出发'],
                        'endcar' => ['num' => '已完成']
                    ];
                    $chartType = 'bar';
                    $data = [];

                    foreach ($types as $t => $v) {
                        if (isset($v['num'])){
                            $data[$t] = ['num' => ['t' => 'n', 'name' => $v['num'], 'type' => $chartType, 'days' => $dates]];
                        }    
                        if (isset($v['price'])){
                            $data[$t]['price'] = ['t' => 'p', 'name' => $v['price'], 'type' => $chartType, 'days' => $dates];
                        }
                    }
                    
                    foreach ($list as $item) {
                        $_type = $item['type'];
                        $_date = $item['date'];
                        $_price = $item['price'];
                        $_num = $item['num'];
                        $data[$_type]['num']['days'][$_date] = $_num;
                        if (isset($data[$_type]['price']))
                            $data[$_type]['price']['days'][$_date] = $_price;
                    }

                    $_data = [];
                    foreach ($data as $item) {
                        foreach ($item as $k1 => $v1) {
                            $d = [];
                            foreach ($v1['days'] as $k2 => $v2)
                                $d[] = $v2;
                            $v1['data'] = $d;
                            $_data[] = $v1;
                        }
                    }

                    $option = [
                        'num'=>[
                            'title' => [],
                            'days' => $_days,
                            'data' => []
                        ],
                        'price'=>[
                            'title' => [],
                            'days' => $_days,
                            'data' => []
                        ]
                    ];

                    foreach ($_data as $row)
                    {
                        if(isset($row['t']) && $row['t']=='n')
                        {
                            $option['num']['title'][] = $row['name'];
                            $option['num']['data'][] = $row;
                        }
                        elseif(isset($row['t']) && $row['t']=='p')
                        {
                            $option['price']['title'][] = $row['name'];
                            $option['price']['data'][] = $row;
                        }
                    }

                    Cm::$res->susess($option);
                    break;        
                case 'open-city':
                    $sql = "SELECT b.name,b.lng,b.lat FROM open_city a LEFT JOIN all_area b ON a.code=b.code WHERE a.status=1 GROUP BY a.code";
                    $city = Cm::$db->all($sql);
                    $option = [];
                    if(!empty($city)){
                        foreach ($city as $key => $value) {
                            if(!empty($value['lat']) && !empty($value['lng'])){
                                $option[] = [
                                    'name' => $value['name'],
                                    'value' => [
                                        $value['lng'],
                                        $value['lat']
                                    ]
                                ];
                            }
                        }
                    }
                    $sql = "SELECT b.name AS sname,b.lng AS slng,b.lat AS slat,c.name AS ename,c.lng AS elng,c.lat AS elat FROM circuit a LEFT JOIN all_area b ON a.city_scode=b.code LEFT JOIN all_area c ON a.city_ecode=c.code WHERE a.status=1";
                    $circuitdata = Cm::$db->all($sql);
                    $circuit = [];
                    if(!empty($circuitdata)){
                        foreach ($circuitdata as $key => $value) {
                            $circuit[] = [
                                'name'=> $value['sname'].'--'.$value['ename'],
                                'sname'=> $value['sname'],
                                'ename'=> $value['ename'],
                                'value' => [
                                    [
                                        $value['slng'],
                                        $value['slat']
                                    ],
                                    [
                                        $value['elng'],
                                        $value['elat']
                                    ]
                                ]
                            ];
                        }
                    }
                    Cm::$res->susess(['city'=>$option,'circuit'=>$circuit]);
                    break;
                case 'feedback-list':
                    $pageIndex = Cm::$req->post('page', ['null', 'empty', 'default' => 1]);
                    $pageCount = Cm::$req->post('limit', ['null', 'empty', 'default' => 20]);
                    $data = Cm::$db->paging("SELECT a.content,a.addtime,b.nickname,b.head_img
                            FROM feedback a 
                            LEFT JOIN user b ON a.uid=b.id
                            WHERE a.status=1 ORDER BY a.addtime DESC",$pageIndex, $pageCount);
                    if(!empty($data['data'])){
                        foreach ($data['data'] as $key => &$value) {
                            $value['head_img'] = empty($value['head_img']) ? '' : $value['head_img'];
                        }
                    }
                    Cm::$res->paging($data);
                    break; 
                case 'order-list':
                    $stime = date("Y-m-d 00:00:00",time());
                    $etime = date("Y-m-d 23:59:59",time());
                    $pageIndex = Cm::$req->post('page', ['null', 'empty', 'default' => 1]);
                    $pageCount = Cm::$req->post('limit', ['null', 'empty', 'default' => 20]);
                    $data = Cm::$db->paging("SELECT a.order_number,a.addtime,a.order_price,b.nickname,b.head_img,c.name AS circuit_name
                            FROM `order` a 
                            LEFT JOIN user b ON a.user_id=b.id
                            LEFT JOIN circuit c ON a.circuit_id=c.id
                            WHERE a.status=1 AND a.addtime>='{$stime}' AND a.addtime<='{$etime}' ORDER BY a.addtime DESC",$pageIndex, $pageCount);
                    if(!empty($data['data'])){
                        foreach ($data['data'] as $key => &$value) {
                            
                        }
                    }
                    Cm::$res->paging($data);
                    break;       
            }
        }

        $mysql = Cm::$db->one("SELECT VERSION() AS version");
        $apaches =  $_SERVER["SERVER_SOFTWARE"];//apache_get_version();
        $apachearr = explode(" ", $apaches);
        $os = empty($apachearr[1]) ? '' : $apachearr[1];
        $data = [
            'php_version' => phpversion(),
            'apache_version' => $apachearr[0],
            'mysql_version' => $mysql['version'],
            'os' => php_uname('s').$os,
            'timezone' => date_default_timezone_get(),
            'yii' => Yii::getVersion(),
        ];
        return $data;
    }
}